/**
 * File: VelvetController.java
 * Created by: mhaimel
 * Created on: 23 Jul 2009
 * CVS:  $Id: VelvetSearchController.java,v 1.1 2009/10/09 14:58:37 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.velvet;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;

import uk.ac.ebi.curtain.controller.SimpleController;
import uk.ac.ebi.curtain.management.InterceptorInfo;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.file.FileInfo;
import uk.ac.ebi.velvet.model.Supercontig;

/**
 * Build a Velvet job from a bucket directory
 * @author mhaimel
 *
 */
public class VelvetSearchController extends SimpleController<File,VelvetInputBean> {

	@Override
	protected VelvetInputBean processData(File bucketDir, InterceptorInfo info) {
		return _findAndSubmit(bucketDir);
	}
	
	private synchronized VelvetInputBean _findAndSubmit(File bucket){
		VelvetInputBean bean = new VelvetInputBean();
		bean.setBaseDir(bucket);
		try{
			File[] listFiles = bucket.listFiles();
			HashSet<File> fIdx = new HashSet<File>(Arrays.asList(listFiles));
			FileInfo ro = Supercontig.getReadOutputFile(bucket);
			if(fIdx.contains(ro.getFile())){
				bean.getInputFiles().put(ro, 0);
			}
			FileInfo ctg = Supercontig.getContigDumpFile(bucket);
			if(fIdx.contains(ctg.getFile())){
				bean.getInputFiles().put(ctg, 0);
			}
			for(Integer c : getContext().getArguments().getCategories()){
				FileInfo pfa = Supercontig.getPairedReadOutputFile(bucket, c);
				bean.getInputFiles().put(pfa, c);
			}
			/*for(File f : listFiles){
				if(f.isFile()){
					String name = f.getName();
					Integer cat = 0;
					FileType fType = FileType.getFromPostfix(name);
					ReadType rType = null;
					if(fType != null ){
						String[] arr = StringUtils.split(name, '_');
						rType = ReadType.valueOf(arr[0]);
						if(rType.isPaired()){
							String[] arr2 = StringUtils.split(arr[1],'.');
							cat = Integer.valueOf(arr2[0]);
							bean.getInputFiles().put(new FileInfo(f,fType,rType), cat);
						} else {	
							bean.getInputFiles().put(new FileInfo(f,fType,rType), cat);
						} 				
					}
				}
			}*/
		}catch (Exception e) {
			throw new CurtainUncheckedException("Problems building bucket: " + bucket,e);
		}
		return bean;
	}
}
